import * as PIXI from 'pixi.js'
import { ResMgr, WidgetManager, IVNODE, VNODE_TYPE } from './widget';

interface IOPTS {
    width: number,
    height: number,
    autoDensity?: boolean,
    view?: HTMLCanvasElement
};

export default class App {
    instance: PIXI.Application
    config: any
    node: IVNODE
    constructor(opts: IOPTS) {
        const defaultOpts = {
            width: 750,
            height: 1334,
            autoDensity: true,
            view: <HTMLCanvasElement>document.getElementById('render-canvas')
        }
        const params = Object.assign(defaultOpts, opts);
        this.config = params;
        const app = new PIXI.Application(params);
        this.instance = app;
        // resize
        window.addEventListener('resize', this.resize.bind(this));
        this.initRootContainer();
        this.resize()
    }

    initRootContainer() {
        const container = new PIXI.Container();
        (<any>container).isRoot = true;
        // 初始化根节点，并设置宽高
        this.node = {
            props: {
                width: this.config.width,
                height: this.config.height,
            },
            type: VNODE_TYPE.DIV,
            link: container
        }
        this.instance.stage.addChild(container);
    }

    loadConfig(configName: string) {
        return new Promise((resolve, reject) => {
            this.instance
                .loader.add(configName)
                .load(() => {
                    ResMgr.init()
                    WidgetManager.init(this.node);
                    resolve();
                });
        })
    }

    resize() {
        const app = this.instance;
        let current = { width: app.renderer.width, height: app.renderer.height };
        let ratio = current.width / current.height;
        if (window.innerWidth / window.innerHeight >= ratio) {
            var width = window.innerHeight * ratio;
            var height = window.innerHeight;
        } else {
            var width = window.innerWidth;
            var height = window.innerWidth / ratio;
        }
        app.view.style.width = `${width}px`;
        app.view.style.height = `${height}px`;
    }
}